const http = require('http')
const url = require('url')
const pry = require('pryjs')
const { version } = require('./package.json')
const logger = require('./src/Logger')
const config = require('./src/Config')
const HandlerResolver = require('./src/HandlerResolver')
const RequestHandler = require('./src/RequestHandler')
const codeMappings = require('./src/CodeMappings')

const handlerResolver = new HandlerResolver()
const requestHandler = new RequestHandler(handlerResolver)

function parseRequest (request, callback) {
  let { pathname, query } = url.parse(request.url, true)
  logger.info('Receive request', pathname, query)
  if (pathname === '/') {
    callback({ path: '/'})
    return
  }

  let data = ''
  request.on('data', function (chunk) {
    data += chunk
  })
  request.on('end', function () {
    logger.verbose('Receive headers', request.headers)
    logger.verbose('Receive data', data)
    callback({ path: pathname, query, data, headers: request.headers, request })
  })
}

function sendResponse (response, body) {
  let status = 200
  if (body.code) {
    logger.info('send code', body.code)
    status = codeMappings[body.code] || 500
  }
  logger.verbose('send data', body)
  response.writeHead(status, { 'Content-Type': 'application/json;charset=utf-8' })
  response.end(JSON.stringify(body, null, 2))
}

http.createServer(function (request, response) {
  parseRequest(request, function (params) {
    if (params.path === '/') {
      sendResponse(response, {
        title: '欢迎使用git-hook小工具',
        version: version
      })
    } else {
      const body = requestHandler.handle(params)
      sendResponse(response, body)
    }
  })
}).listen(config.port, err => {
  if (err) {
    console.log(`Something bad happened: ${err}.`)
  } else {
    console.log(`Server is listening on ${config.port}.`)
  }
})
